package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.common.utils.DownloadUtil;
import com.itheima.common.utils.UtilFuns;
import com.itheima.doamin.cargo.Contract;
import com.itheima.doamin.cargo.ContractExample;
import com.itheima.doamin.cargo.ContractProductVo;
import com.itheima.doamin.cargo.ExtCproductExample;
import com.itheima.doamin.system.User;
import com.itheima.service.cargo.ContractService;
import com.itheima.web.controller.BaseController;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController {
    @Reference
    private ContractService contractService;
    //查询所有合同
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "5") int size){
        //获取查询的条件对象
        ContractExample contractExample=new ContractExample();
        //查询条件对象
        ContractExample.Criteria criteria = contractExample.createCriteria();
        /**
         *0-saas管理员   不能查看企业信息
         *1-企业管理员   能查看本公司的所有信息
         *2-管理所有下属部门和人员  能查看本部门和子部门的信息
         *3-管理本部门   能查看本部门的信息
         *4-普通员工     只能查看自己创建的表信息
         */
        //获得用户的等级
        User currentUser = getCurrentUser();
        int degree=currentUser.getDegree();
        switch (degree){
            case 0:
                throw new RuntimeException("滚！你不能查看企业的任何信息");
            case 1:
                //查询本公司的所有信息
                criteria.andCompanyIdEqualTo(currentUser.getCompanyId());
                break;
            case 2:
                //查询本部门和子部门的信息
                criteria.andCreateDeptLike(currentUser.getDeptId()+"%");
                break;
            case 3:
                //只能查询本部门的信息
                criteria.andCreateDeptEqualTo(currentUser.getDeptId());
                break;
            case 4:
                //查看自己的表信息
                criteria.andCreateByEqualTo(currentUser.getUserName());
                break;
        }
        //排序
        contractExample.setOrderByClause("create_time desc");
        //查询
        PageInfo pageInfo = contractService.findAll(contractExample, page, size);
        request.setAttribute("page",pageInfo);
        return "cargo/contract/contract-list";
    }

    //添加
    @RequestMapping("toAdd")
    public String toAdd(){
        return "cargo/contract/contract-add";
    }

    //更新
    @RequestMapping("toUpdate")
    public String toUpdate(String id){
        request.setAttribute("contract",contractService.findById(id));
        return "cargo/contract/contract-update";
    }

    //查询更新
    @RequestMapping("edit")
    public String edit(Contract contract){
        if (UtilFuns.isEmpty(contract.getId())){
            //保存
            contract.setCompanyId(super.getCurrentUser().getCompanyId());
            contract.setCompanyName(super.getCurrentUser().getCompanyName());
            //添加
            contractService.save(contract);
        }else {
            //更新
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list";
    }


    //改变合同的状态，已报运
    @RequestMapping("submit")
    public String toSubmit(String id){
        Contract contract=new Contract();
        contract.setId(id);
        contract.setState(1);
        contractService.update(contract);
        return "redirect:/cargo/contract/list";
    }

    //变回草稿状态
    @RequestMapping("cancel")
    public String toCancel(String id){
        Contract contract=new Contract();
        contract.setId(id);
        contract.setState(0);
        contractService.update(contract);
        return "redirect:/cargo/contract/list";
    }

    //合同的详细信息
    @RequestMapping("toView")
    public String toView(String id){
        request.setAttribute("contract",contractService.findById(id));
        return "cargo/contract/contract-view";
    }

    @RequestMapping("checkReportStatus")
    public @ResponseBody String checkReportStatus(String id){
        Contract byId = contractService.findById(id);
        if (byId.getState()>1){
            return "true";
        }else {
            return "false";
        }
    }

    /**
     * 删除
     */
    @RequestMapping("delete")
    public String delete(String id){
        //先删除合同下的所有货物
        //创建查询条件
        ExtCproductExample extCproductExample=new ExtCproductExample();
        ExtCproductExample.Criteria criteria = extCproductExample.createCriteria();
        criteria.andContractIdEqualTo(id);

        //获取所有合同根据条件获得所有附件进行删除
        contractService.delete(id);

        return "redirect:/cargo/contract/list";
    }

    //下载页面跳转
    @RequestMapping("print")
    public String print(){
        return "cargo/print/contract-print";
    }


    //套取模板的样式
    //对查到的数据进行下载
    @RequestMapping("printExcel")
    public void printExcel(String inputDate) throws Exception {
        //从数据库查询所需的数据
        List<ContractProductVo> contractProductVos=
                contractService.selectAllContractVo(inputDate,getCurrentUser().getCompanyId());
        //获取样式模板对象
        String realPath = request.getSession().getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx");
        //创建excel对象
        Workbook workbook=new XSSFWorkbook(realPath);
        //创建一张表
        Sheet sheet = workbook.getSheetAt(0);
        //创建表标题
        int rowNum=0;
        Row rowBigTitle = sheet.getRow(rowNum++);
        //设置值e
        Cell cellBigTitle =rowBigTitle.getCell(1);
        String shipDateStr=inputDate.replaceAll("-0","年").replaceAll("-","年");
        cellBigTitle.setCellValue(shipDateStr+"月出货表");

        //创建小标题
        rowNum++;


        //使用集合获取到单元格的样式
        List<CellStyle> cellStyleList=new ArrayList<>();
        //获取第三行
        Row contextStyleRow = sheet.getRow(rowNum);
        //为样式集合中加入样式数据
        for (int i=1;i<9;i++){
            //获取到第三行的样式
            CellStyle cellStyle = contextStyleRow.getCell(i).getCellStyle();
            cellStyleList.add(cellStyle);
        }
        //遍历集合把查到的数据写入单元格中
        for (int j=0;j<contractProductVos.size();j++){
            int colNum=1;
            //创建单元一行
            Row dataRow = sheet.createRow(rowNum++);
            //创建单元格并为单元格加入数据
            Cell context1=dataRow.createCell(colNum++);
            context1.setCellStyle(cellStyleList.get(0));
            context1.setCellValue(contractProductVos.get(j).getCustomName());
            Cell context2=dataRow.createCell(colNum++);
            context2.setCellStyle(cellStyleList.get(1));
            context2.setCellValue(contractProductVos.get(j).getContractNo());
            Cell context3=dataRow.createCell(colNum++);
            context3.setCellStyle(cellStyleList.get(2));
            context3.setCellValue(contractProductVos.get(j).getProductNo());
            Cell context4=dataRow.createCell(colNum++);
            context4.setCellStyle(cellStyleList.get(3));
            context4.setCellValue(contractProductVos.get(j).getCnumber());
            Cell context5=dataRow.createCell(colNum++);
            context5.setCellStyle(cellStyleList.get(4));
            context5.setCellValue(contractProductVos.get(j).getFactoryName());
            Cell context6=dataRow.createCell(colNum++);
            context6.setCellStyle(cellStyleList.get(5));
            context6.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVos.get(j).getDeliveryPeriod()));
            Cell context7=dataRow.createCell(colNum++);
            context7.setCellStyle(cellStyleList.get(6));
            context7.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVos.get(j).getShipTime()));
            Cell context8=dataRow.createCell(colNum++);
            context8.setCellStyle(cellStyleList.get(7));
            context8.setCellValue(contractProductVos.get(j).getTradeTerms());
        };

    //自己写的的样式
    //对查到的数据进行下载
//    @RequestMapping("printExcel1")
//    public void printExcel1(String inputDate) throws Exception {
//        //从数据库查询所需的数据
//        List<ContractProductVo> contractProductVos=
//                contractService.selectAllContractVo(inputDate,getCurrentUser().getCompanyId());
//        //创建excel对象
//        Workbook workbook=new XSSFWorkbook();
//        //创建一张表
//        Sheet sheet = workbook.createSheet();
//        sheet.setColumnWidth(0,6*256);
//        sheet.setColumnWidth(1,26*256);
//        sheet.setColumnWidth(2,12*256);
//        sheet.setColumnWidth(3,30*256);
//        sheet.setColumnWidth(4,12*256);
//        sheet.setColumnWidth(5,15*256);
//        sheet.setColumnWidth(6,10*256);
//        sheet.setColumnWidth(7,10*256);
//        sheet.setColumnWidth(8,10*256);
//        //创建表标题
//        int rowNum=0;
//        Row rowBigTitle = sheet.createRow(rowNum++);
//        //设置值e
//        Cell cellBigTitle =rowBigTitle.createCell(1);
//        cellBigTitle.setCellStyle(bigTitle(workbook)); //设置大标题样式
//        //合并单元格 参数1 开始行  参数2 结束行  参数3 开始列  参数4  结束列
//        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
//        String shipDateStr=inputDate.replaceAll("-0","年").replaceAll("-","年");
//        cellBigTitle.setCellValue
//                (shipDateStr+"月出货表");
//        //创建小标题
//        Row rowSmallTitle = sheet.createRow(rowNum++);
//        List<String> smallTitle=new ArrayList<>();
//        Collections.addAll(smallTitle,"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款");
//        //遍历向行中的单元格加入数据
//        for (int i=0;i<smallTitle.size();i++){
//            Cell smallTitleCell = rowSmallTitle.createCell(i + 1);
//            smallTitleCell.setCellValue(smallTitle.get(i));
//            smallTitleCell.setCellStyle(title(workbook));//设置小标题样式;
//        }
//
//        //遍历集合把查到的数据写入单元格中
//
//        for (int j=0;j<contractProductVos.size();j++){
//            int colNum=1;
//            //创建单元格
//            Row dataRow = sheet.createRow(rowNum++);
//            //创建单元格并为单元格加入数据
//
//            Cell context1=dataRow.createCell(colNum++);
//            context1.setCellStyle(text(workbook));
//            context1.setCellValue(contractProductVos.get(j).getCustomName());
//            Cell context2=dataRow.createCell(colNum++);
//            context2.setCellStyle(text(workbook));
//            context2.setCellValue(contractProductVos.get(j).getContractNo());
//            Cell context3=dataRow.createCell(colNum++);
//            context3.setCellStyle(text(workbook));
//            context3.setCellValue(contractProductVos.get(j).getProductNo());
//            Cell context4=dataRow.createCell(colNum++);
//            context4.setCellStyle(text(workbook));
//            context4.setCellValue(contractProductVos.get(j).getCnumber());
//            Cell context5=dataRow.createCell(colNum++);
//            context5.setCellStyle(text(workbook));
//            context5.setCellValue(contractProductVos.get(j).getFactoryName());
//            Cell context6=dataRow.createCell(colNum++);
//            context6.setCellStyle(text(workbook));
//            context6.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVos.get(j).getDeliveryPeriod()));
//            Cell context7=dataRow.createCell(colNum++);
//            context7.setCellStyle(text(workbook));
//            context7.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVos.get(j).getShipTime()));
//            Cell context8=dataRow.createCell(colNum++);
//            context8.setCellStyle(text(workbook));
//            context8.setCellValue(contractProductVos.get(j).getTradeTerms());
//        };

        //无样式
        //对查到的数据进行下载
//        @RequestMapping("printExcel")
//        public void printExcel(String inputDate) throws Exception {
//            //从数据库查询所需的数据
//            List<ContractProductVo> contractProductVos=
//                    contractService.selectAllContractVo(inputDate,getCurrentUser().getCompanyId());
//            //创建excel对象
//            Workbook workbook=new SXSSFWorkbook();
//            //创建一张表
//            Sheet sheet = workbook.createSheet();
//
//            //创建表标题
//            int rowNum=0;
//            Row rowBigTitle = sheet.createRow(rowNum++);
//            //设置值e
//            Cell cellBigTitle =rowBigTitle.createCell(1);
//            String shipDateStr=inputDate.replaceAll("-0","年").replaceAll("-","年");
//            cellBigTitle.setCellValue(shipDateStr+"月出货表");
//            //创建小标题
//            Row rowSmallTitle = sheet.createRow(rowNum++);
//            List<String> smallTitle=new ArrayList<>();
//            Collections.addAll(smallTitle,"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款");
//            //遍历向行中的单元格加入数据
//            for (int i=0;i<smallTitle.size();i++){
//                Cell smallTitleCell = rowSmallTitle.createCell(i + 1);
//                smallTitleCell.setCellValue(smallTitle.get(i));
//            }
//
//            //遍历集合把查到的数据写入单元格中
//            for (int j=0;j<contractProductVos.size();j++){
//                for (int i=0;i<=6000;i++){
//                    int colNum=1;
//                    //创建单元格
//                    Row dataRow = sheet.createRow(rowNum++);
//                    //创建单元格并为单元格加入数据
//
//                    Cell context1=dataRow.createCell(colNum++);
//                    context1.setCellValue(contractProductVos.get(j).getCustomName());
//                    Cell context2=dataRow.createCell(colNum++);
//                    context2.setCellValue(contractProductVos.get(j).getContractNo());
//                    Cell context3=dataRow.createCell(colNum++);
//                    context3.setCellValue(contractProductVos.get(j).getProductNo());
//                    Cell context4=dataRow.createCell(colNum++);
//                    context4.setCellValue(contractProductVos.get(j).getCnumber());
//                    Cell context5=dataRow.createCell(colNum++);
//                    context5.setCellValue(contractProductVos.get(j).getFactoryName());
//                    Cell context6=dataRow.createCell(colNum++);
//                    context6.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVos.get(j).getDeliveryPeriod()));
//                    Cell context7=dataRow.createCell(colNum++);
//                    context7.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVos.get(j).getShipTime()));
//                    Cell context8=dataRow.createCell(colNum++);
//                    context8.setCellValue(contractProductVos.get(j).getTradeTerms());
//                }
//
//            };



        //创建输出流
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        new DownloadUtil().download(byteArrayOutputStream,response,"出货表.xlsx");
    }

    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细
        return style;
    }
}
